<template>
    <div class="e-form">
        <BillTop title="采购验收详情" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="采购验收明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.handoverPurchase"  label-width="160px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="验收编号：">
                                            <span>{{ formData.handoverPurchase.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="验收日期：" prop="acceptanceDate">
                                            <span>{{formData.handoverPurchase.acceptanceDate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="验收人：">
                                            <span>{{ formData.handoverPurchase.founderName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="购置日期：" prop="purchaseDate">
                                            <span>{{formData.handoverPurchase.purchaseDate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同名称：" prop="contractName">
                                            <span>{{formData.handoverPurchase.contractName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="供应单位：">
                                            <span>{{ formData.handoverPurchase.supplierName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="验收地点：" prop="acceptanceSiteDetails">
                                            <!-- <span>{{ typeof formData.handoverPurchase.acceptanceSiteDetails=='string' ?formData.handoverPurchase.acceptanceSiteDetails: showAddress(formData.handoverPurchase.acceptanceSiteDetails)}}</span> -->
                                            <span>{{showAddress(formData.handoverPurchase.acceptanceSiteDetails)}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                <el-col :span="12">
                                        <el-form-item label="管理单位：" prop="managementUnit">
                                            <span>{{formData.handoverPurchase.managementUnit}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                        <span>{{ statusLable(formData.handoverPurchase.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="机构：">
                                            <span>{{formData.handoverPurchase.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item  label="备注：">
                                        <span>{{formData.handoverPurchase.remarks}}</span>
                                    </el-form-item>
                                </el-row>
                                <el-row v-if="formData.handoverPurchase.state === 5">
                                        <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.handoverPurchase.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{formData.handoverPurchase.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="formData.handoverPurchase.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                formData.handoverPurchase.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                formData.handoverPurchase.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">采购验收明细</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="handoverPurchaseDtlListCopy"
                                border
                                style="width: 100%"
                                v-sortTable="{ 'tableData': handoverPurchaseDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentNo"
                                    label="设备编号"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="180"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="100"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="purchasePrice"
                                    label="设备原值（元）"
                                    width="130"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="stipulatedServiceLife"
                                    label="规定使用年限"
                                    width="130"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.stipulatedServiceLife}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="manufacturer"
                                    label="生产厂商"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.manufacturer}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="originalNum"
                                    label="原厂编号"
                                    width="180"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.originalNum}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="productionDate"
                                    label="出厂日期"
                                    width="180"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.productionDate}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="activeNo"
                                    label="主动力编号"
                                    width="180"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.activeNo}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="activeModel"
                                    label="主动力型号"
                                    width="200"
                                    align="center"
                                >
                                   <template slot-scope="{ row }">
                                       <span>{{row.activeModel}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="activeManufacturer"
                                    label="主动力生产厂家"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.activeManufacturer}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="activeProductionDate"
                                    label="主动力出厂日期"
                                    width="180"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.activeProductionDate}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="powerful"
                                    label="功率"
                                    width="100"
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="plateNumber"
                                    label="车牌编号"
                                    width="180"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.plateNumber}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="useage"
                                    label="技术参数"
                                    width="120"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-button size="mini" class="btn-blue" @click="paramsAdd(row)"
                                            >查看</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" isView bucketName="facilityconnect" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="4011"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.handoverPurchase.state" @exas="exas" :founderId="formData.handoverPurchase.founderId" />
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/purchaseAcceptance.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { getCurrentUnitInfo, history } from '@/api/equip/handoverAudit.js'
import { openAppClient, hideLoading, showLoading } from '@/utils/common'
import { exas } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //采购验收基础信息
                handoverPurchase: {
                    'acceptanceDate': '',
                    'acceptanceSite': '',
                    'acceptanceSiteDetails': '',
                    'acceptanceSiteList': [],
                    'acceptanceSiteNumber': '',
                    'auditDate': '',
                    'auditor': '',
                    'auditorId': '',
                    'billDate': '',
                    'billNo': '',
                    'contractId': '',
                    'contractName': '',
                    'contractNo': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'managementId': '',
                    'managementUnit': '',
                    'modifier': '',
                    'modifierId': '',
                    'orgId': '',
                    'orgName': '',
                    'purchaseDate': '',
                    'purchaseId': '',
                    'founderName': '',
                    'founderId': '',
                    'remarks': '',
                    'state': '0',
                    'supplierId': '',
                    'supplierName': '',
                    'workId': ''
                },
            },
            billid: this.$route.query.billid,
            handoverPurchaseDtlList: [],
            handoverPurchaseDtlListCopy: [],
            auditHistoryTable: [],
            planSelect: [], //采购验收明细选择项
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            currentRow: {},
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 4011,
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 4011,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj ? obj.label : ''
            }
        },
        //当前单据状态
        state () {
            return this.formData.handoverPurchase.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        showAddress () {
            return value=>{
                if(!value) return ''
                const obj = JSON.parse(value)
                const address = obj.address ? obj.address.join('-') : ''
                const detail = obj.detail
                let str = ''
                if(address && detail) {
                    str = address + '-' + detail
                }else if(!address  && detail) {
                    str = detail
                }else if(address  && !detail) {
                    str = address
                }
                return str
            }
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()
            ]).finally(() => {
                hideLoading()
            })
        },
        getInfo () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.purchaseAcceptanceBaseInfo(params).then(res=>{
                this.formData.handoverPurchase = res.handoverPurchase
            })
        },
        getPlanList () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.purchaseAcceptancePlanInfo(params).then(res=>{
                this.handoverPurchaseDtlListCopy = []
                this.handoverPurchaseDtlList = res.handoverPurchaseDtlList
                res.handoverPurchaseDtlList.map(item=>{
                    this.handoverPurchaseDtlListCopy.push(item)
                })
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取状态按钮
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //========计划明细============
        //获取参数信息
        paramsAdd (row) {
            this.setAuditParams({ id: row.leaseExitId })
            // 客户端弹窗弹出本地页面
            openAppClient('/skillParameterShow', '参数查看')
        },
        //取消
        handleClose () {
            this.$router.replace('/purchaseAcceptanceList')
        },
        //更新基础信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.form.validate(valid => {
                    if(valid) {
                        request.purchaseAcceptanceUpdate(this.formData).then(()=>{
                            resolve()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                        })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateDetailInfo () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    request.updatePurchaseAcceptanceDel(this.handoverPurchaseDtlList).then(()=>{
                        resolve()
                    }).catch(err=>{
                        reject(err)
                        this.setError('planDetail')
                    })
                }).catch(err=>{
                    this.setError('planDetail')
                    reject(err)
                })

            })
        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.updateDetailInfo()
            ])
                .then(() => {
                    this.clientPop('suc', '保存成功')
                    this.init()
                })
                .catch(() => {
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 1)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

</style>
